﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CloudReader.Net.Protocol;

namespace CloudReader.Net
{
    public class DynamicBuffer:IDisposable
    {
        int offset;
        int m_capacity;
        readonly int m_size;
        int totalCount;
        int maxCount;
        byte[] m_buffer;
        Parser parser;

        public DynamicBuffer()
        {
            m_size = 4096;
            m_capacity = 4;
            offset = totalCount = 0;
            maxCount = m_size * m_capacity;
            m_buffer = new byte[maxCount];
            parser = new Parser();
        }
        private void EnsureCapacity(int length)
        {
            if(maxCount < length + totalCount)
            {
                //扩充数组
                var pro = m_buffer;
                m_capacity *= 2;
                maxCount = m_capacity * m_size;
                m_buffer = new byte[maxCount];
                Array.Copy(pro, m_buffer, pro.Length);
            }
        }
        public void Enqueue(byte[] data)
        {
            EnsureCapacity(data.Length);//确定是否扩容
            totalCount += data.Length;
            Array.Copy(data, 0, m_buffer, offset, data.Length);
            offset += data.Length;
            if (Parser.isEOF(data))
            {
                RecieveCompleted(GetData());
            }
        }
        public CloudReaderPackage GetData()
        {
            var p = new byte[totalCount];
            Array.Copy(p, m_buffer, totalCount);
            totalCount = 0;
            return Parser.Decode(p);
        }
        public void Dispose()
        {
            GC.SuppressFinalize(this);
        }
        public event Action<CloudReaderPackage> RecieveCompleted;
    }
}
